package com.test.jbpm.dao.impl;

import java.sql.SQLException;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.test.jbpm.Pager;
import com.test.jbpm.dao.UserDao;
import com.test.jbpm.domain.Dept;
import com.test.jbpm.domain.User;


@Repository
public class UserDaoImpl extends BaseDao implements UserDao {

	public void addOrUpdate(User user) {
		try {
			  user.setDept((Dept) getHibernateTemplate().load(Dept.class,1));
			getHibernateTemplate().saveOrUpdate(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("ok");
	}

	public void del(Integer userId) {
			getHibernateTemplate().delete(getHibernateTemplate().load(User.class, userId));
	}

	public User findUserById(Integer userId) {
		return (User)getHibernateTemplate().load(User.class, userId);
	}

	@SuppressWarnings("unchecked")
	public Pager<User> findUserList() {
		return findData("from User");
	}

	public User login(final String userCode, final String password) {
		return (User)getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				return session.createQuery("from User u where u.code=? and u.password=?")
							.setParameter(0, userCode)
							.setParameter(1, password)
							.uniqueResult();
			}
		});
	}

}
